﻿using System.Collections;
using UnityEngine;

public class FadeEffect : MonoBehaviour
{
    public CanvasGroup canvasGroup; // 引用Canvas Group组件
    private float fadeDuration = 0.3f; // 淡入淡出持续时间

    private Coroutine fadeCoroutine; // 用于存储协程引用，以便可以停止它


    public void FadeIn()
    {
        canvasGroup.alpha = 0;
        gameObject.SetActive(true);
        if (fadeCoroutine != null) StopCoroutine(fadeCoroutine); // 如果已有协程在运行，则停止它
        fadeCoroutine = StartCoroutine(Fade(1, fadeDuration)); // 开始淡入协程
    }

    public void FadeOut()
    {
        if (fadeCoroutine != null) StopCoroutine(fadeCoroutine); // 如果已有协程在运行，则停止它
        fadeCoroutine = StartCoroutine(Fade(0, fadeDuration)); // 开始淡出协程
    }

    private IEnumerator Fade(float targetAlpha, float duration)
    {
        float currentTime = 0;
        float startAlpha = canvasGroup.alpha; // 记录开始时的透明度
        while (currentTime < duration)
        {
            currentTime += Time.deltaTime;
            canvasGroup.alpha = Mathf.Lerp(startAlpha, targetAlpha, currentTime / duration); // 线性插值计算当前透明度
            yield return null; // 等待下一帧
        }
        canvasGroup.alpha = targetAlpha; // 确保透明度达到目标值
        if(targetAlpha==0)
        {
            gameObject.SetActive(false);
        }
    }
}